import { departList } from './data'
import Mock from 'mockjs'
import { getNowDateTime } from '../../utils'
export default [
  {
    url: '/system/depart/create', // 新增
    method: 'post',
    response: data => {
      insert(data)
      return {
        code: 200,
        status: true,
        msg: '成功！',
        data: null
      }
    }
  },
  {
    url: '/system/depart/update', // 修改
    method: 'put',
    response: data => {
      updateById(data)
      return {
        code: 200,
        status: true,
        msg: '成功！',
        data: null
      }
    }
  },
  {
    url: RegExp('/system/depart/delete' + '.*'), // 删除
    method: 'delete',
    response: params => {
      deleteById(params)
      return {
        code: 200,
        status: true,
        msg: '成功！',
        data: null
      }
    }
  },
  {
    url: RegExp('/system/depart/detail' + '.*'), // 获取详情
    method: 'get',
    response: params => {
      return {
        code: 200,
        status: true,
        msg: '成功！',
        data: getInfoById(params)
      }
    }
  },
  {
    url: RegExp('/system/depart/list' + '.*'), // 查询列表
    method: 'get',
    response: () => {
      return {
        code: 200,
        status: true,
        msg: '成功！',
        data: getList()
      }
    }
  },
  {
    url: RegExp('/system/depart/simple-list' + '.*'), // 查询简化列表
    method: 'get',
    response: () => {
      return {
        code: 200,
        status: true,
        msg: '成功！',
        data: getListBySimple()
      }
    }
  }
]

const getList = () => {
  let result = departList
  result = result.filter(item => !item.deleted)
  return result
}

const getListBySimple = () => {
  return departList
    .filter(item => item.status === 0 && !item.deleted)
    .map(item => ({
      id: item.id,
      parentId: item.parentId,
      name: item.name,
      sort: item.sort,
      leaderUserId: item.leaderUserId,
      mobile: item.mobile,
      email: item.email,
      status: item.status,
      remark: item.remark
    }))
}

const insert = data => {
  departList.unshift({
    ...data.body,
    id: Mock.Random.id(),
    creator: '1',
    create_time: getNowDateTime(),
    updater: '',
    update_time: '',
    deleted: false,
    deleted_time: ''
  })
}

const updateById = data => {
  departList.forEach(item => {
    if (item.id === data.body.id) {
      Object.keys(data.body).forEach(v => {
        item[v] = data.body[v]
      })
      item.updater = '1'
      item.update_time = getNowDateTime()
    }
  })
}

const deleteById = params => {
  departList.forEach(item => {
    if (item.id === parseInt(params.query.id)) {
      item.deleted = true
      item.updater = '1'
      item.update_time = getNowDateTime()
      item.deleted_time = getNowDateTime()
    }
  })
}

const getInfoById = params => {
  const result = departList.filter(item => {
    return item.id === parseInt(params.query.id)
  })
  if (result.length > 0) {
    return result[0]
  } else {
    return null
  }
}
